package com.css.zfzx.sjcj.modules.hddcB7_VolcanicDataTable.service.impl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.css.zfzx.sjcj.common.superRepository.SuperRepository;
import com.css.zfzx.sjcj.common.utils.EasyPoiExcelUtil;
import com.css.zfzx.sjcj.common.utils.UpdateUtil;
import com.css.zfzx.sjcj.modules.hddcB7_VolcanicDataTable.repository.HddcB7VolcanicdatatableNativeRepository;
import com.css.zfzx.sjcj.modules.hddcB7_VolcanicDataTable.repository.HddcB7VolcanicdatatableRepository;
import com.css.zfzx.sjcj.modules.hddcB7_VolcanicDataTable.repository.entity.HddcB7VolcanicdatatableEntity;
import com.css.zfzx.sjcj.modules.hddcB7_VolcanicDataTable.service.HddcB7VolcanicdatatableService;
import com.css.zfzx.sjcj.modules.hddcB7_VolcanicDataTable.viewobjects.HddcB7VolcanicdatatableQueryParams;
import com.css.zfzx.sjcj.modules.hddcB7_VolcanicDataTable.viewobjects.HddcB7VolcanicdatatableVO;
import com.css.bpm.platform.api.local.PlatformAPI;
import com.css.bpm.platform.sys.dict.repository.entity.DictItemEntity;
import com.css.bpm.platform.utils.*;
import com.css.zfzx.sjcj.modules.hddcGeophySvyLine.repository.entity.HddcGeophysvylineEntity;
import com.css.zfzx.sjcj.modules.hddcGeophySvyPoint.repository.entity.HddcGeophysvypointEntity;
import com.css.zfzx.sjcj.modules.hddcVolcanicSamplePoint.repository.entity.HddcVolcanicsamplepointEntity;
import com.css.zfzx.sjcj.modules.hddcVolcanicSamplePoint.service.HddcVolcanicsamplepointService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * @author zhangcong
 * @date 2020-11-26
 */
@Service
public class HddcB7VolcanicdatatableServiceImpl implements HddcB7VolcanicdatatableService {

    @Autowired
    private HddcB7VolcanicdatatableRepository hddcB7VolcanicdatatableRepository;
    @Autowired
    private HddcB7VolcanicdatatableNativeRepository hddcB7VolcanicdatatableNativeRepository;
    @Autowired
    private HddcVolcanicsamplepointService hddcVolcanicsamplepointService;

    @Override
    public JSONObject queryHddcB7Volcanicdatatables(HddcB7VolcanicdatatableQueryParams queryParams, int curPage, int pageSize, String sort, String order) {
        Page<HddcB7VolcanicdatatableEntity> hddcB7VolcanicdatatablePage = this.hddcB7VolcanicdatatableNativeRepository.queryHddcB7Volcanicdatatables(queryParams, curPage, pageSize, sort, order);
        JSONObject jsonObject = PlatformPageUtils.formatPageData(hddcB7VolcanicdatatablePage);
        return jsonObject;
    }


    @Override
    public HddcB7VolcanicdatatableEntity getHddcB7Volcanicdatatable(String id) {
        HddcB7VolcanicdatatableEntity hddcB7Volcanicdatatable = this.hddcB7VolcanicdatatableRepository.findById(id).orElse(null);
        return hddcB7Volcanicdatatable;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HddcB7VolcanicdatatableEntity saveHddcB7Volcanicdatatable(HddcB7VolcanicdatatableEntity hddcB7Volcanicdatatable) {
        String uuid = UUIDGenerator.getUUID();
        hddcB7Volcanicdatatable.setUuid(uuid);
        hddcB7Volcanicdatatable.setQualityinspectionStatus("0");
        hddcB7Volcanicdatatable.setCreateUser(PlatformSessionUtils.getUserId());
        hddcB7Volcanicdatatable.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
        hddcB7Volcanicdatatable.setIsValid("1");
        this.hddcB7VolcanicdatatableRepository.save(hddcB7Volcanicdatatable);
        return hddcB7Volcanicdatatable;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HddcB7VolcanicdatatableEntity updateHddcB7Volcanicdatatable(HddcB7VolcanicdatatableEntity hddcB7Volcanicdatatable) {
        UpdateUtil.copyNullProperties(hddcB7VolcanicdatatableRepository.findByUuidAndIsValid(hddcB7Volcanicdatatable.getUuid(), "1"), hddcB7Volcanicdatatable);
        hddcB7Volcanicdatatable.setUpdateUser(PlatformSessionUtils.getUserId());
        hddcB7Volcanicdatatable.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
        this.hddcB7VolcanicdatatableRepository.save(hddcB7Volcanicdatatable);
        return hddcB7Volcanicdatatable;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteHddcB7Volcanicdatatables(List<String> ids) {
        List<HddcB7VolcanicdatatableEntity> hddcB7VolcanicdatatableList = this.hddcB7VolcanicdatatableRepository.findAllById(ids);
        if (!PlatformObjectUtils.isEmpty(hddcB7VolcanicdatatableList) && hddcB7VolcanicdatatableList.size() > 0) {
            for (HddcB7VolcanicdatatableEntity hddcB7Volcanicdatatable : hddcB7VolcanicdatatableList) {
//                this.hddcB7VolcanicdatatableRepository.delete(hddcB7Volcanicdatatable);
                hddcB7Volcanicdatatable.setIsValid("0");
                hddcB7Volcanicdatatable.setUpdateUser(PlatformSessionUtils.getUserId());
                hddcB7Volcanicdatatable.setUpdateTime(new Date());
                this.hddcB7VolcanicdatatableRepository.save(hddcB7Volcanicdatatable);
            }
        }
    }

    @Override
    public List<DictItemEntity> getValidDictItemsByDictCode(String dictCode) {
        List<DictItemEntity> validDictItems = PlatformAPI.getDictAPI().getValidDictItemsByDictCode(dictCode);
        return validDictItems;
    }

    @Override
    public void exportFile(HddcB7VolcanicdatatableQueryParams queryParams, HttpServletResponse response) {
        List<HddcB7VolcanicdatatableEntity> yhDisasterEntities = hddcB7VolcanicdatatableNativeRepository.exportYhDisasters(queryParams);
        List<HddcB7VolcanicdatatableVO> list = new ArrayList<>();
        for (HddcB7VolcanicdatatableEntity entity : yhDisasterEntities) {
            HddcB7VolcanicdatatableVO yhDisasterVO = new HddcB7VolcanicdatatableVO();
            BeanUtils.copyProperties(entity, yhDisasterVO);
            list.add(yhDisasterVO);
        }
        EasyPoiExcelUtil.exportExcel(list, "火山地质调查填图数据表", "火山地质调查填图数据表", HddcB7VolcanicdatatableVO.class, "火山地质调查填图数据表.xls", response);
    }

    @Override
    public String exportExcel(MultipartFile file, HttpServletResponse response) {
        try {
            // 返回的消息
            StringBuilder returnMsg = new StringBuilder();
            // 导入的参数信息
            ImportParams params = new ImportParams();
            // 设置简析的第一行
            params.setHeadRows(1);
            // 是否需要校验
            params.setNeedVerify(true);
            // 获取到Excel数据
            ExcelImportResult<HddcB7VolcanicdatatableVO> result = ExcelImportUtil.importExcelMore(file.getInputStream(), HddcB7VolcanicdatatableVO.class, params);
            List<HddcB7VolcanicdatatableVO> list = result.getList();
            // Excel条数据
            int firstList = list.size();
            StringBuilder sb = new StringBuilder();
            //保存
            saveDisasterList(list, sb);
            returnMsg.append("成功导入" + (result.getList().size()));
            returnMsg.append(sb);
            if (result.isVerifyFail()) {
                // 校验返回失败行信息
                Iterator<HddcB7VolcanicdatatableVO> iterator = result.getFailList().iterator();
                while (iterator.hasNext()) {
                    HddcB7VolcanicdatatableVO yhDisasterVO = iterator.next();
                    String error = "";
                    returnMsg.append("第" + yhDisasterVO.getRowNum() + "行" + yhDisasterVO.getErrorMsg() + "<br/>");
                    returnMsg.append(error);
                }
            }
            return returnMsg.toString();
        } catch (Exception e) {

            return "导入失败，请检查数据正确性";
        }
    }

    @Autowired
    SuperRepository superRepository;

    @Override
    @Transactional
    public int dataQualityCheck() {
        List<HddcB7VolcanicdatatableEntity> listAll = hddcB7VolcanicdatatableRepository.findByAll();
        List<HddcB7VolcanicdatatableEntity> updateList = new ArrayList<>();
        for (HddcB7VolcanicdatatableEntity b2All : listAll) {
            String str = "";
            if (StringUtils.isEmpty(b2All.getSamplepointid())) {
                str += "【火山地质调查填图数据表】采样点编号为空。";
            }else {
                HddcVolcanicsamplepointEntity hddcVolcanicsamplepointEntity = hddcVolcanicsamplepointService.findById(b2All.getSamplepointid());
                if (hddcVolcanicsamplepointEntity == null) {
                    str += "【火山地质调查填图数据表】表单中采样点编号与【火山采样点】表单中采样点编号不一致。";
                }else {
                    if (StringUtils.isEmpty(b2All.getFieldid())){
                        str += "【火山地质调查填图数据表】野外编号为空。";
                    }
                    if (!hddcVolcanicsamplepointEntity.getFieldid().equals(b2All.getFieldid())) {
                        str += "【火山地质调查填图数据表】表单中野外编号与【火山采样点】表单中野外编号不一致。";
                    }
                }
            }
            if(str.isEmpty()){
                str +="【火山地质调查填图数据表】与【火山采样点】质检成功。";
                b2All.setQualityinspectionStatus("1");
            }else{
                b2All.setQualityinspectionStatus("2");
            }
            b2All.setQualityinspectionComments(null);
            String[] split = str.split("。");
            for (int i = 0; i < split.length; i++) {
                if (i == 0) {
                    b2All.setExtends1(split[i]);
                    b2All.setExtends2(null);
                    b2All.setExtends3(null);
                } else if (i == 1) {
                    b2All.setExtends2(split[i]);
                    b2All.setExtends3(null);
                } else if (i == 2) {
                    b2All.setExtends3(split[i]);
                }
            }
            updateList.add(b2All);
        }
        superRepository.batchUpdate(updateList);
        return 1;
    }

    /**
     * 批量存入库表并且返回错误数量
     *
     * @param list
     * @param message
     * @return
     */
    public void saveDisasterList(List<HddcB7VolcanicdatatableVO> list, StringBuilder message) {
        for (int i = 0; i < list.size(); i++) {
            HddcB7VolcanicdatatableEntity yhDisasterEntity = new HddcB7VolcanicdatatableEntity();
            HddcB7VolcanicdatatableVO yhDisasterVO = list.get(i);
            // 将VO数据映射拷贝到库表中
            BeanUtils.copyProperties(yhDisasterVO, yhDisasterEntity);
            saveHddcB7Volcanicdatatable(yhDisasterEntity);
        }
    }

}
